<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>更新学生信息 - 学生信息管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#0FC6C2',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        gray: {
                            50: '#F5F7FA',
                            100: '#E5E6EB',
                            200: '#C9CDD4',
                            300: '#86909C',
                            400: '#4E5969',
                            500: '#272E3B',
                            600: '#1D2129',
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .btn-hover {
                @apply transition-all duration-300 hover:shadow-lg transform hover:-translate-y-0.5;
            }
            .form-focus {
                @apply focus:ring-2 focus:ring-primary/30 focus:border-primary focus:outline-none;
            }
            .field-label {
                @apply block text-sm font-medium text-gray-600 mb-1;
            }
            .error-message {
                @apply text-danger text-xs mt-1 block;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans min-h-screen">
    <!-- 导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-50">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-3">
                <i class="fa fa-graduation-cap text-primary text-2xl"></i>
                <h1 class="text-xl font-bold text-gray-600">学生信息管理系统</h1>
            </div>
            <nav class="hidden md:flex items-center space-x-8">
                <a href="index.html" class="text-gray-400 hover:text-primary transition-colors">首页</a>
                <a href="all-students.html" class="text-gray-400 hover:text-primary transition-colors">全部学生</a>
                <a href="student-by-id.html" class="text-gray-400 hover:text-primary transition-colors">ID查询</a>
                <a href="students-by-status.html" class="text-gray-400 hover:text-primary transition-colors">状态查询</a>
                <a href="students-by-name.html" class="text-gray-400 hover:text-primary transition-colors">姓名查询</a>
                <a href="update-student.html" class="text-primary font-medium">信息更新</a>
            </nav>
            <button class="md:hidden text-gray-500">
                <i class="fa fa-bars text-xl"></i>
            </button>
        </div>
    </header>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-8">
        <div class="mb-8">
            <div class="flex items-center space-x-3 mb-2">
                <a href="index.html" class="text-gray-400 hover:text-primary transition-colors">
                    <i class="fa fa-home"></i>
                </a>
                <i class="fa fa-angle-right text-gray-300 text-xs"></i>
                <span class="text-gray-400">信息更新</span>
            </div>
            <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-gray-600">更新学生信息</h2>
            <p class="text-gray-400">输入学生ID，修改并更新学生信息</p>
        </div>

        <!-- 学生ID查询 -->
        <div id="studentIdFormSection" class="bg-white rounded-xl p-6 card-shadow mb-8">
            <h3 class="text-lg font-semibold text-gray-600 mb-4">查找学生</h3>
            <form id="studentIdForm" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="space-y-2">
                        <label for="studentId" class="field-label">
                            <span class="text-danger">*</span> 学生ID
                        </label>
                        <div class="relative">
                            <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-400">
                                <i class="fa fa-id-card"></i>
                            </span>
                            <input 
                                type="text" 
                                id="studentId" 
                                name="studentId" 
                                placeholder="请输入学生ID" 
                                required
                                class="w-full pl-10 pr-4 py-2.5 border border-gray-200 rounded-lg form-focus"
                            >
                        </div>
                        <p class="text-xs text-gray-400">请输入完整的学生ID以查找要更新的学生信息</p>
                    </div>
                </div>
                
                <div class="pt-4 flex flex-wrap gap-4">
                    <button type="submit" class="px-6 py-2.5 bg-primary text-white rounded-lg font-medium flex items-center btn-hover">
                        <i class="fa fa-search mr-2"></i>查找学生
                    </button>
                    <button type="reset" class="px-6 py-2.5 bg-gray-100 text-gray-600 rounded-lg font-medium flex items-center hover:bg-gray-200 transition-colors">
                        <i class="fa fa-refresh mr-2"></i>重置
                    </button>
                    <button type="button" id="viewAllBtn" class="px-6 py-2.5 bg-gray-100 text-gray-600 rounded-lg font-medium flex items-center hover:bg-gray-200 transition-colors">
                        <i class="fa fa-list mr-2"></i>查看全部
                    </button>
                </div>
            </form>
        </div>

        <!-- 更新表单 -->
        <div id="updateFormSection" class="bg-white rounded-xl p-6 card-shadow mb-8 hidden">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-lg font-semibold text-gray-600">更新学生信息</h3>
                <div class="text-sm text-gray-400">
                    上次更新时间: <span id="lastUpdateTime"></span>
                </div>
            </div>
            
            <form id="updateForm" class="space-y-6">
                <input type="hidden" id="updateStudentId" name="studentId">
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- 基本信息 -->
                    <div class="space-y-4">
                        <div class="space-y-2">
                            <label for="name" class="field-label">
                                <span class="text-danger">*</span> 姓名
                            </label>
                            <input 
                                type="text" 
                                id="name" 
                                name="name" 
                                placeholder="请输入学生姓名" 
                                required
                                class="w-full px-4 py-2.5 border border-gray-200 rounded-lg form-focus"
                            >
                            <span id="nameError" class="error-message hidden"></span>
                        </div>
                        
                        <div class="space-y-2">
                            <label for="className" class="field-label">班级</label>
                            <input 
                                type="text" 
                                id="className" 
                                name="className" 
                                placeholder="请输入班级信息" 
                                class="w-full px-4 py-2.5 border border-gray-200 rounded-lg form-focus"
                            >
                        </div>
                        
                        <div class="space-y-2">
                            <label for="major" class="field-label">专业</label>
                            <input 
                                type="text" 
                                id="major" 
                                name="major" 
                                placeholder="请输入专业信息" 
                                class="w-full px-4 py-2.5 border border-gray-200 rounded-lg form-focus"
                            >
                        </div>
                        
                        <div class="space-y-2">
                            <label for="gender" class="field-label">性别</label>
                            <select 
                                id="gender" 
                                name="gender" 
                                class="w-full px-4 py-2.5 border border-gray-200 rounded-lg form-focus appearance-none bg-white"
                            >
                                <option value="">请选择性别</option>
                                <option value="男">男</option>
                                <option value="女">女</option>
                            </select>
                        </div>
                    </div>
                    
                    <!-- 联系信息 -->
                    <div class="space-y-4">
                        <div class="space-y-2">
                            <label for="phone" class="field-label">手机号码</label>
                            <input 
                                type="tel" 
                                id="phone" 
                                name="phone" 
                                placeholder="请输入手机号码" 
                                pattern="^1[3-9]\d{9}$"
                                class="w-full px-4 py-2.5 border border-gray-200 rounded-lg form-focus"
                            >
                            <span id="phoneError" class="error-message hidden"></span>
                        </div>
                        
                        <div class="space-y-2">
                            <label for="email" class="field-label">电子邮箱</label>
                            <input 
                                type="email" 
                                id="email" 
                                name="email" 
                                placeholder="请输入电子邮箱" 
                                class="w-full px-4 py-2.5 border border-gray-200 rounded-lg form-focus"
                            >
                            <span id="emailError" class="error-message hidden"></span>
                        </div>
                        
                        <div class="space-y-2">
                            <label for="status" class="field-label">
                                <span class="text-danger">*</span> 学生状态
                            </label>
                            <select 
                                id="status" 
                                name="status" 
                                required
                                class="w-full px-4 py-2.5 border border-gray-200 rounded-lg form-focus appearance-none bg-white"
                            >
                                <option value="1">正常</option>
                                <option value="0">已删除</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="border-t border-gray-100 pt-6 flex flex-wrap gap-4 justify-between">
                    <button type="button" id="cancelUpdateBtn" class="px-6 py-2.5 bg-gray-100 text-gray-600 rounded-lg font-medium flex items-center hover:bg-gray-200 transition-colors">
                        <i class="fa fa-times mr-2"></i>取消
                    </button>
                    <div class="flex gap-4">
                        <button type="button" id="resetFormBtn" class="px-6 py-2.5 bg-gray-100 text-gray-600 rounded-lg font-medium flex items-center hover:bg-gray-200 transition-colors">
                            <i class="fa fa-refresh mr-2"></i>重置表单
                        </button>
                        <button type="submit" class="px-6 py-2.5 bg-primary text-white rounded-lg font-medium flex items-center btn-hover">
                            <i class="fa fa-save mr-2"></i>保存更新
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- 成功提示 -->
        <div id="successMessage" class="bg-white rounded-xl p-8 card-shadow text-center hidden">
            <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-success/10 text-success mb-4">
                <i class="fa fa-check-circle text-2xl"></i>
            </div>
            <h3 class="text-lg font-semibold text-gray-600 mb-2">更新成功</h3>
            <p class="text-gray-400 max-w-md mx-auto mb-6">学生信息已成功更新到系统</p>
            <div class="flex flex-wrap justify-center gap-4">
                <button id="newUpdateBtn" class="px-6 py-2.5 bg-primary text-white rounded-lg font-medium flex items-center btn-hover">
                    <i class="fa fa-plus mr-2"></i>更新其他学生
                </button>
                <a href="student-by-id.html" id="viewStudentBtn" class="px-6 py-2.5 bg-gray-100 text-gray-600 rounded-lg font-medium flex items-center hover:bg-gray-200 transition-colors">
                    <i class="fa fa-eye mr-2"></i>查看学生信息
                </a>
                <a href="index.html" class="px-6 py-2.5 bg-gray-100 text-gray-600 rounded-lg font-medium flex items-center hover:bg-gray-200 transition-colors">
                    <i class="fa fa-home mr-2"></i>返回首页
                </a>
            </div>
        </div>

        <!-- 错误提示 -->
        <div id="errorMessage" class="bg-white rounded-xl p-8 card-shadow text-center hidden">
            <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-danger/10 text-danger mb-4">
                <i class="fa fa-exclamation-circle text-2xl"></i>
            </div>
            <h3 class="text-lg font-semibold text-gray-600 mb-2">操作失败</h3>
            <p class="text-gray-400 max-w-md mx-auto mb-6" id="errorDetails"></p>
            <button id="retryBtn" class="px-6 py-2.5 bg-primary text-white rounded-lg font-medium flex items-center btn-hover mx-auto">
                <i class="fa fa-refresh mr-2"></i>重新尝试
            </button>
        </div>

        <!-- 加载提示 -->
        <div id="loadingIndicator" class="bg-white rounded-xl p-8 card-shadow text-center hidden">
            <div class="inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary mb-4"></div>
            <h3 class="text-lg font-semibold text-gray-600 mb-2">正在处理</h3>
            <p class="text-gray-400" id="loadingText">请稍候，系统正在处理您的请求...</p>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white mt-12 py-6 border-t border-gray-100">
        <div class="container mx-auto px-4 text-center text-gray-400 text-sm">
            <p>© 2023 学生信息管理系统 - 版权所有</p>
        </div>
    </footer>

    <!-- JavaScript -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 表单元素
            const studentIdForm = document.getElementById('studentIdForm');
            const updateForm = document.getElementById('updateForm');
            const studentIdInput = document.getElementById('studentId');
            
            // 页面区域
            const studentIdFormSection = document.getElementById('studentIdFormSection');
            const updateFormSection = document.getElementById('updateFormSection');
            const successMessage = document.getElementById('successMessage');
            const errorMessage = document.getElementById('errorMessage');
            const errorDetails = document.getElementById('errorDetails');
            const loadingIndicator = document.getElementById('loadingIndicator');
            const loadingText = document.getElementById('loadingText');
            
            // 按钮
            const viewAllBtn = document.getElementById('viewAllBtn');
            const cancelUpdateBtn = document.getElementById('cancelUpdateBtn');
            const resetFormBtn = document.getElementById('resetFormBtn');
            const retryBtn = document.getElementById('retryBtn');
            const newUpdateBtn = document.getElementById('newUpdateBtn');
            const viewStudentBtn = document.getElementById('viewStudentBtn');
            
            // 更新表单字段
            const formFields = {
                studentId: document.getElementById('updateStudentId'),
                name: document.getElementById('name'),
                className: document.getElementById('className'),
                major: document.getElementById('major'),
                gender: document.getElementById('gender'),
                phone: document.getElementById('phone'),
                email: document.getElementById('email'),
                status: document.getElementById('status'),
                lastUpdateTime: document.getElementById('lastUpdateTime')
            };
            
            // 错误提示元素
            const errorElements = {
                name: document.getElementById('nameError'),
                phone: document.getElementById('phoneError'),
                email: document.getElementById('emailError')
            };
            
            // 当前编辑的学生ID
            let currentStudentId = '';
            
            // 事件监听器
            studentIdForm.addEventListener('submit', function(e) {
                e.preventDefault();
                const studentId = studentIdInput.value.trim();
                
                if (!studentId) {
                    showError('请输入学生ID');
                    return;
                }
                
                findStudentById(studentId);
            });
            
            updateForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                if (validateForm()) {
                    updateStudentInfo();
                }
            });
            
            viewAllBtn.addEventListener('click', function() {
                window.location.href = 'all-students.html';
            });
            
            cancelUpdateBtn.addEventListener('click', function() {
                resetPage();
            });
            
            resetFormBtn.addEventListener('click', function() {
                resetFormErrors();
            });
            
            retryBtn.addEventListener('click', function() {
                errorMessage.classList.add('hidden');
                studentIdFormSection.classList.remove('hidden');
            });
            
            newUpdateBtn.addEventListener('click', function() {
                resetPage();
            });
            
            // 输入验证
            formFields.phone.addEventListener('input', function() {
                validatePhone(this.value);
            });
            
            formFields.email.addEventListener('input', function() {
                validateEmail(this.value);
            });
            
            formFields.name.addEventListener('input', function() {
                validateName(this.value);
            });
            
            // 重置页面
            function resetPage() {
                studentIdForm.reset();
                updateForm.reset();
                resetFormErrors();
                
                studentIdFormSection.classList.remove('hidden');
                updateFormSection.classList.add('hidden');
                successMessage.classList.add('hidden');
                errorMessage.classList.add('hidden');
                loadingIndicator.classList.add('hidden');
                
                currentStudentId = '';
                studentIdInput.focus();
            }
            
            // 重置表单错误
            function resetFormErrors() {
                Object.values(errorElements).forEach(el => el.classList.add('hidden'));
                Object.values(formFields).forEach(field => {
                    if (field.tagName === 'INPUT' || field.tagName === 'SELECT') {
                        field.classList.remove('border-danger');
                    }
                });
            }
            
            // 显示加载状态
            function showLoading(text = '请稍候，系统正在处理您的请求...') {
                loadingText.textContent = text;
                studentIdFormSection.classList.add('hidden');
                updateFormSection.classList.add('hidden');
                successMessage.classList.add('hidden');
                errorMessage.classList.add('hidden');
                loadingIndicator.classList.remove('hidden');
            }
            
            // 显示错误
            function showError(message) {
                errorDetails.textContent = message || '操作失败，请稍后重试';
                loadingIndicator.classList.add('hidden');
                studentIdFormSection.classList.add('hidden');
                updateFormSection.classList.add('hidden');
                successMessage.classList.add('hidden');
                errorMessage.classList.remove('hidden');
            }
            
            // 显示成功信息
            function showSuccess() {
                loadingIndicator.classList.add('hidden');
                updateFormSection.classList.add('hidden');
                successMessage.classList.remove('hidden');
                
                // 更新查看学生按钮的链接
                viewStudentBtn.href = `student-by-id.html?id=${currentStudentId}`;
            }
            
            // 格式化时间
            function formatDate(dateString) {
                if (!dateString) return '-';
                
                const date = new Date(dateString);
                if (isNaN(date.getTime())) return '-';
                
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            }
            
            // 验证姓名
            function validateName(name) {
                const errorElement = errorElements.name;
                const field = formFields.name;
                
                if (!name.trim()) {
                    showFieldError(field, errorElement, '姓名不能为空');
                    return false;
                } else if (name.length > 50) {
                    showFieldError(field, errorElement, '姓名不能超过50个字符');
                    return false;
                } else {
                    hideFieldError(field, errorElement);
                    return true;
                }
            }
            
            // 验证手机号
            function validatePhone(phone) {
                const errorElement = errorElements.phone;
                const field = formFields.phone;
                
                if (!phone) {
                    hideFieldError(field, errorElement);
                    return true;
                }
                
                const phonePattern = /^1[3-9]\d{9}$/;
                if (!phonePattern.test(phone)) {
                    showFieldError(field, errorElement, '请输入有效的手机号码');
                    return false;
                } else {
                    hideFieldError(field, errorElement);
                    return true;
                }
            }
            
            // 验证邮箱
            function validateEmail(email) {
                const errorElement = errorElements.email;
                const field = formFields.email;
                
                if (!email) {
                    hideFieldError(field, errorElement);
                    return true;
                }
                
                const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailPattern.test(email)) {
                    showFieldError(field, errorElement, '请输入有效的邮箱地址');
                    return false;
                } else {
                    hideFieldError(field, errorElement);
                    return true;
                }
            }
            
            // 显示字段错误
            function showFieldError(field, errorElement, message) {
                field.classList.add('border-danger');
                errorElement.textContent = message;
                errorElement.classList.remove('hidden');
            }
            
            // 隐藏字段错误
            function hideFieldError(field, errorElement) {
                field.classList.remove('border-danger');
                errorElement.classList.add('hidden');
            }
            
            // 表单验证
            function validateForm() {
                let isValid = true;
                
                if (!validateName(formFields.name.value)) isValid = false;
                if (!validatePhone(formFields.phone.value)) isValid = false;
                if (!validateEmail(formFields.email.value)) isValid = false;
                
                return isValid;
            }
            
            // 查找学生信息
            function findStudentById(studentId) {
                showLoading('正在查找学生信息...');
                
                fetch(`/getStudentById/${studentId}`)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP error! Status: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (!data || Object.keys(data).length === 0) {
                            throw new Error('未找到该学生的信息');
                        }
                        
                        // 填充表单
                        currentStudentId = data.studentId;
                        formFields.studentId.value = data.studentId || '';
                        formFields.name.value = data.name || '';
                        formFields.className.value = data.className || '';
                        formFields.major.value = data.major || '';
                        formFields.gender.value = data.gender || '';
                        formFields.phone.value = data.phone || '';
                        formFields.email.value = data.email || '';
                        formFields.status.value = data.status !== undefined ? data.status : 1;
                        formFields.lastUpdateTime.textContent = formatDate(data.updateTime);
                        
                        // 显示更新表单
                        loadingIndicator.classList.add('hidden');
                        studentIdFormSection.classList.add('hidden');
                        updateFormSection.classList.remove('hidden');
                        
                        // 平滑滚动到更新表单
                        updateFormSection.scrollIntoView({ behavior: 'smooth' });
                    })
                    .catch(error => {
                        console.error('查找学生失败:', error);
                        showError(error.message);
                    });
            }
            
            // 更新学生信息
            function updateStudentInfo() {
                showLoading('正在更新学生信息...');
                
                const formData = new FormData(updateForm);
                const studentData = Object.fromEntries(formData.entries());
                
                fetch('/updateStudent', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(studentData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! Status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    // 假设后端返回 {"success": true} 表示成功
                    if (data && data.success) {
                        showSuccess();
                    } else {
                        throw new Error('更新失败，服务器返回错误');
                    }
                })
                .catch(error => {
                    console.error('更新学生信息失败:', error);
                    showError('更新失败，请稍后重试');
                });
            }
            
            // 检查URL参数，支持从其他页面带ID跳转
            const urlParams = new URLSearchParams(window.location.search);
            const studentIdParam = urlParams.get('id');
            if (studentIdParam) {
                studentIdInput.value = studentIdParam;
                studentIdForm.dispatchEvent(new Event('submit'));
            }
            
            // 自动聚焦输入框
            studentIdInput.focus();
        });
    </script>
</body>
</html>